// @Author EthanScriptOn
// @Desc
package config_source_loader

import (
	"fmt"
	"strings"
)

type SourceLoaderSlicing struct {
	SlicingTag     string
	TrimWhiteSpace bool
	NSegments      int
}

func GenerateSourceLoaderSlicing(slicingTag string, trimWhiteSpace bool, nSegments int) *SourceLoaderSlicing {
	return &SourceLoaderSlicing{
		SlicingTag:     slicingTag,
		TrimWhiteSpace: trimWhiteSpace,
		NSegments:      nSegments,
	}
}

func (s *SourceLoaderSlicing) Split(line string) []string {
	return strings.SplitN(line, s.SlicingTag, s.NSegments)
}

func (s *SourceLoaderSlicing) GetIndex(line string, index int) (string, error) {
	segments := strings.SplitN(line, s.SlicingTag, s.NSegments)
	if len(segments) <= 0 {
		return "", fmt.Errorf("for %v cutting, it is expected to cut %v segments and ultimately obtain %v segments slicingTag is %v", line, s.NSegments, len(segments), s.SlicingTag)
	}
	if len(segments)-1 < index {
		return "", fmt.Errorf("for %v cutting, it is expected to cut %v segments and ultimately obtain %v segments the index you want to obtain is %v slicingTag is %v", line, s.NSegments, len(segments), index, s.SlicingTag)
	}
	if s.TrimWhiteSpace {
		return strings.TrimSpace(segments[index]), nil
	}
	return segments[index], nil
}

func (s *SourceLoaderSlicing) GetFirst(line string) (string, error) {
	segments := strings.SplitN(line, s.SlicingTag, s.NSegments)
	if len(segments) <= 0 {
		return "", fmt.Errorf("for %v cutting, it is expected to cut %v segments and ultimately obtain %v segments slicingTag is %v", line, s.NSegments, len(segments), s.SlicingTag)
	}
	if s.TrimWhiteSpace {
		return strings.TrimSpace(segments[0]), nil
	}
	return segments[0], nil
}

func (s *SourceLoaderSlicing) GetLast(line string) (string, error) {
	segments := strings.SplitN(line, s.SlicingTag, s.NSegments)
	if len(segments) <= 0 {
		return "", fmt.Errorf("for %v cutting, it is expected to cut %v segments and ultimately obtain %v segments slicingTag is %v", line, s.NSegments, len(segments), s.SlicingTag)
	}
	if s.TrimWhiteSpace {
		return strings.TrimSpace(segments[len(segments)-1]), nil
	}
	return segments[len(segments)-1], nil
}

func (s *SourceLoaderSlicing) Requirements(line string) bool {
	return strings.ContainsAny(line, s.SlicingTag)
}
